package com.sailfish.springbootdemo.configs;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

@Configuration(value = "db8")  // 修改为 db8
@MapperScan(basePackages = "com.sailfish.springbootdemo.dao.db8", sqlSessionFactoryRef = "SqlServerSqlSessionFactory8")
public class SQLServer8Config {

    @Bean(name = "SqlServerDataSource8")
    @ConfigurationProperties(prefix = "spring.datasource.db8")  // 调整前缀为 db8
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "SqlServerTransactionManager8")
    public DataSourceTransactionManager transactionManager(@Qualifier("SqlServerDataSource8") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SqlServerSqlSessionFactory8")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("SqlServerDataSource8") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 若需 XML 映射文件，指定路径（如 classpath*:mapper/sqlserver8/*.xml）
        return bean.getObject();
    }

    @Bean("SqlServerSqlSessionTemplate8")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("SqlServerSqlSessionFactory8") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}